import React, { useState, useEffect } from 'react';
import {
  Modal,
  Table,
  Button,
  Form,
  Input,
  Select,
  message,
  Space,
  Tag,
  Avatar,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Card,
  Statistic,
  List,
  Divider,
} from 'antd';
import {
  UserAddOutlined,
  UserDeleteOutlined,
  TeamOutlined,
  CrownOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import {
  addParticipantsApi,
  removeParticipantApi,
} from '../../../api/checkin';

const { Option } = Select;

const ParticipantManagement = ({ visible, mainActivity, onCancel, onSuccess }) => {
  const [loading, setLoading] = useState(false);
  const [participants, setParticipants] = useState([]);
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [form] = Form.useForm();

  // 获取当前用户ID
  const getCurrentUserId = () => 1; // 临时写死，实际应该从登录状态获取

  // 模拟参与者数据，实际应该从API获取
  const mockParticipants = [
    { id: 1, name: '张三', role: 'creator', joinedAt: '2025-01-01', status: 'active' },
    { id: 2, name: '李四', role: 'participant', joinedAt: '2025-01-02', status: 'active' },
    { id: 3, name: '王五', role: 'participant', joinedAt: '2025-01-03', status: 'active' },
    { id: 4, name: '赵六', role: 'participant', joinedAt: '2025-01-04', status: 'inactive' },
  ];

  // 模拟用户列表，实际应该从API获取
  const mockUsers = [
    '钱七', '孙八', '周九', '吴十', '郑十一', '王十二', '冯十三', '陈十四', '褚十五', '卫十六'
  ];

  // 当主活动变化时，获取参与者列表
  useEffect(() => {
    if (visible && mainActivity) {
      fetchParticipants();
    }
  }, [visible, mainActivity]);

  // 获取参与者列表
  const fetchParticipants = async () => {
    try {
      setLoading(true);
      // 这里应该调用实际的API
      // const response = await getParticipantsApi({ mainCheckinId: mainActivity.id });
      // if (response && response.code === '0') {
      //   setParticipants(response.data || []);
      // }
      
      // 临时使用模拟数据
      setParticipants(mockParticipants);
    } catch (error) {
      console.error('获取参与者列表失败:', error);
      message.error('获取参与者列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理添加参与者
  const handleAddParticipants = () => {
    form.resetFields();
    setIsAddModalVisible(true);
  };

  // 处理移除参与者
  const handleRemoveParticipant = async (participantId, participantName) => {
    try {
      // 这里应该调用实际的API
      // const response = await removeParticipantApi({
      //   mainCheckinId: mainActivity.id,
      //   participant: participantName
      // });
      
      // 临时模拟成功
      message.success('移除成功');
      setParticipants(prev => prev.filter(p => p.id !== participantId));
      onSuccess();
    } catch (error) {
      console.error('移除失败:', error);
      message.error('移除失败');
    }
  };

  // 处理添加参与者提交
  const handleAddSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 这里应该调用实际的API
      // const response = await addParticipantsApi({
      //   mainCheckinId: mainActivity.id,
      //   participants: values.participants
      // });
      
      // 临时模拟成功
      const newParticipants = values.participants.map((name, index) => ({
        id: Date.now() + index,
        name,
        role: 'participant',
        joinedAt: dayjs().format('YYYY-MM-DD'),
        status: 'active'
      }));
      
      setParticipants(prev => [...prev, ...newParticipants]);
      message.success('添加成功');
      setIsAddModalVisible(false);
      form.resetFields();
      onSuccess();
    } catch (error) {
      console.error('添加失败:', error);
      message.error('添加失败');
    }
  };

  // 参与者表格列定义
  const columns = [
    {
      title: '参与者',
      key: 'participant',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar size="small" style={{ marginRight: 8 }}>
            {record.name.charAt(0)}
          </Avatar>
          <div>
            <div style={{ fontWeight: 'bold' }}>{record.name}</div>
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.role === 'creator' ? '创建者' : '参与者'}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 100,
      render: (role) => (
        <Tag color={role === 'creator' ? 'gold' : 'blue'} icon={role === 'creator' ? <CrownOutlined /> : <TeamOutlined />}>
          {role === 'creator' ? '创建者' : '参与者'}
        </Tag>
      ),
    },
    {
      title: '加入时间',
      dataIndex: 'joinedAt',
      key: 'joinedAt',
      width: 120,
      render: (date) => dayjs(date).format('MM-DD'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '活跃' : '非活跃'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Space size="small">
          {record.role !== 'creator' && (
            <Tooltip title="移除参与者">
              <Popconfirm
                title={`确定要移除 ${record.name} 吗？`}
                onConfirm={() => handleRemoveParticipant(record.id, record.name)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  danger
                  icon={<UserDeleteOutlined />}
                />
              </Popconfirm>
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  return (
    <>
      <Modal
        title={`管理参与者 - ${mainActivity?.title}`}
        visible={visible}
        onCancel={onCancel}
        footer={null}
        width={1000}
        destroyOnClose
      >
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="总参与人数"
                value={participants.length}
                suffix="人"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="活跃参与者"
                value={participants.filter(p => p.status === 'active').length}
                suffix="人"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="创建者"
                value={participants.filter(p => p.role === 'creator').length}
                suffix="人"
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic
                title="普通参与者"
                value={participants.filter(p => p.role === 'participant').length}
                suffix="人"
              />
            </Card>
          </Col>
        </Row>

        {/* 参与者列表 */}
        <Card
          title="参与者列表"
          extra={
            <Button
              type="primary"
              icon={<UserAddOutlined />}
              onClick={handleAddParticipants}
            >
              添加参与者
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={participants}
            loading={loading}
            rowKey="id"
            pagination={false}
            size="small"
          />
        </Card>

        {/* 参与者统计 */}
        <Card title="参与者统计" size="small" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col span={12}>
              <h4>角色分布</h4>
              <div style={{ marginTop: 8 }}>
                <Tag color="gold" icon={<CrownOutlined />}>
                  创建者: {participants.filter(p => p.role === 'creator').length} 人
                </Tag>
                <Tag color="blue" icon={<TeamOutlined />}>
                  参与者: {participants.filter(p => p.role === 'participant').length} 人
                </Tag>
              </div>
            </Col>
            <Col span={12}>
              <h4>状态分布</h4>
              <div style={{ marginTop: 8 }}>
                <Tag color="green">活跃: {participants.filter(p => p.status === 'active').length} 人</Tag>
                <Tag color="red">非活跃: {participants.filter(p => p.status === 'inactive').length} 人</Tag>
              </div>
            </Col>
          </Row>
        </Card>
      </Modal>

      {/* 添加参与者模态框 */}
      <Modal
        title="添加参与者"
        visible={isAddModalVisible}
        onCancel={() => {
          setIsAddModalVisible(false);
          form.resetFields();
        }}
        footer={[
          <Button 
            key="cancel" 
            onClick={() => {
              setIsAddModalVisible(false);
              form.resetFields();
            }}
          >
            取消
          </Button>,
          <Button 
            key="submit" 
            type="primary" 
            onClick={handleAddSubmit}
          >
            添加
          </Button>,
        ]}
        width={500}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="选择参与者"
            name="participants"
            rules={[
              { required: true, message: '请选择参与者' },
              { type: 'array', min: 1, message: '至少选择一个参与者' }
            ]}
          >
            <Select
              mode="multiple"
              placeholder="请选择要添加的参与者"
              optionLabelProp="label"
              showSearch
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {mockUsers.map(user => (
                <Option key={user} value={user} label={user}>
                  {user}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <div style={{ textAlign: 'center', color: '#666', fontSize: 12 }}>
            <p>💡 提示：选择的用户将收到活动邀请通知</p>
          </div>
        </Form>
      </Modal>
    </>
  );
};

export default ParticipantManagement; 